package hu.mapro.gwtui.gxt.client.recordseditor.requestfactory.valuelist;

import hu.mapro.gwtui.client.Action;
import hu.mapro.gwtui.client.Handlers;

import com.google.inject.Singleton;
import com.google.web.bindery.requestfactory.shared.BaseProxy;
import com.google.web.bindery.requestfactory.shared.Receiver;

@Singleton
public class ValueDataCache<T extends BaseProxy> {

	ValueDataLoaderInterface<T> dataStore;
	
	public ValueDataCache(ValueDataLoaderInterface<T> dataStore) {
		super();
		this.dataStore = dataStore;
	}

	Handlers updateHandlers = Handlers.newInstance();
	T cachedData;

	public void fireWhenLoaded(final Action action) {

		fireWhenLoaded(new Receiver<T>() {
			@Override
			public void onSuccess(T response) {
				action.perform();
			}
		});
		
	}
	
	public void fireWhenLoaded(final Receiver<T> receiver) {
		
		if (cachedData==null) {
			dataStore.loadData().fire(createReceiver(receiver));
		} else {
			receiver.onSuccess(cachedData);
		}
		
	}

	Receiver<T> createReceiver(final Receiver<T> receiver) {
		return new Receiver<T>() {
			@Override
			public void onSuccess(T response) {
				set(response);
				receiver.onSuccess(response);
			}
		};
	}

	public Handlers getUpdateHandlers() {
		return updateHandlers;
	}

	public void set(T response) {
		cachedData = response;
		updateHandlers.fire();
	}
	
}
